package io.renren.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Lists;
import io.renren.utils.*;
import io.renren.utils.excel.ExportExcel;
import io.renren.utils.excel.ImportExcel;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import io.renren.entity.EmpInfoModifyEntity;
import io.renren.service.EmpInfoModifyService;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;


/**
 * 员工信息修改
 * 
 * @author zhangheng
 * @email zh_123shmily@163.com
 * @date 2017-07-12 11:06:28
 */
@RestController
@RequestMapping("empinfomodify")
public class EmpInfoModifyController {
	@Autowired
	private EmpInfoModifyService empInfoModifyService;
	
	/**
	 * 列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("empinfomodify:list")
	public R list(@RequestParam Map<String, Object> params,HttpServletRequest request, HttpServletResponse response){
//        if("export".equals(params.get("op"))){
//            return exportFile(request,response, (List<EmpInfoModifyEntity>) getPageUtils(params).getList());
//        }else{
            return R.ok().put("page", getPageUtils(params));
        //}
	}

    public PageUtils getPageUtils(Map<String, Object> params){
        //查询列表数据
        Query query = new Query(params);

        List<EmpInfoModifyEntity> empInfoModifyList = empInfoModifyService.queryList(query);
        int total = empInfoModifyService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(empInfoModifyList, total, query.getLimit(), query.getPage());
        return pageUtil;
    }
	/**
	 * 信息
	 */
	@RequestMapping("/info/{id}")
	@RequiresPermissions("empinfomodify:info")
	public R info(@PathVariable("id") Integer id){
		EmpInfoModifyEntity empInfoModify = empInfoModifyService.queryObject(id);
		
		return R.ok().put("empInfoModify", empInfoModify);
	}
	
	/**
	 * 保存
	 */
	@RequestMapping("/save")
	@RequiresPermissions("empinfomodify:save")
	public R save(@RequestBody EmpInfoModifyEntity empInfoModify){
		empInfoModifyService.save(empInfoModify);
		
		return R.ok();
	}
	
	/**
	 * 修改
	 */
	@RequestMapping("/update")
	@RequiresPermissions("empinfomodify:update")
	public R update(@RequestBody EmpInfoModifyEntity empInfoModify){
		empInfoModifyService.update(empInfoModify);
		
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("empinfomodify:delete")
	public R delete(@RequestBody Integer[] ids){
		empInfoModifyService.deleteBatch(ids);
		
		return R.ok();
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("empinfomodify:list")
	@RequestMapping(value = "/list/export", method = RequestMethod.GET)
	public String exportFile(HttpServletRequest request, HttpServletResponse response/*, @RequestParam Map<String, Object> params*/) {
		try {
			String op =request.getParameter("op");
			List<EmpInfoModifyEntity> list =null;
			if("export".equals(op)){//导出数据
				 list = empInfoModifyService.selectAllrecord();
			}else if("download".equals(op)){//下载模板
				 list = Lists.newArrayList();
			}
			String fileName = "员工信息" + DateUtils.format(new Date(),"yyyyMMddHHmmss") + ".xlsx";
            new ExportExcel("员工信息", EmpInfoModifyEntity.class).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			//throw new RRException("导出求职者信息管理记录失败！失败信息：" + e.getMessage());
		}
		System.out.println("out!!!");
		return "redirect:empinfomodify/list";
	}
	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("empinfomodify:import")
	@RequestMapping(value ="/import", method = RequestMethod.POST,headers={"Content-Type=multipart/form-data"})
	public R importFile(@RequestParam("file") MultipartFile file) {
		try {
				if (!file.isEmpty()) {
				String filename = file.getOriginalFilename();
				//提取后缀
				String postfix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
				if(!".xls".equals(postfix)&&!".xlsx".equals(postfix)){
					throw new RRException("文件格式不正确");
				}
				int successNum = 0;
				int failureNum = 0;
				StringBuilder failureMsg = new StringBuilder();
				ImportExcel ei = new ImportExcel(file, 1, 0);
				List<EmpInfoModifyEntity> list = ei.getDataList(EmpInfoModifyEntity.class);
				for (EmpInfoModifyEntity empnum : list){
					try{
						empInfoModifyService.save(empnum);
						successNum++;
					}catch(ConstraintViolationException ex){
						failureNum++;
					}catch (Exception ex) {
						failureNum++;
					}
				}
				if (failureNum>0){
					failureMsg.insert(0, "，失败 "+failureNum+" 条预警记录。");
				}
				throw new RRException("已成功导入 "+successNum+" 条 求职人员编号自动生成记录"+failureMsg);
			}else{
				throw new RRException("上传失败:请添加上传文件！");
			}
		} catch (RRException e) {
			throw e;
		}catch (Exception e) {
			//throw new RRException("导入 求职人员编号自动生成失败！失败信息："+e.getMessage());
		}
		return R.ok();
	}
}
